package com.gmail.hy87cn.hellohi.client.connect;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.reveregroup.gwt.facebook4gwt.Facebook;
import com.reveregroup.gwt.facebook4gwt.LoginButton;
import com.reveregroup.gwt.facebook4gwt.events.FacebookLoginEvent;
import com.reveregroup.gwt.facebook4gwt.events.FacebookLoginHandler;
import com.reveregroup.gwt.facebook4gwt.user.FacebookUser;
import com.reveregroup.gwt.facebook4gwt.user.UserField;

/**
 * @author HeYi
 * 
 */
public class FacebookUi extends Composite {

	private static FacebookUiUiBinder uiBinder = GWT
			.create(FacebookUiUiBinder.class);

	interface FacebookUiUiBinder extends UiBinder<Widget, FacebookUi> {
	}

	@UiField
	FlowPanel flowPanel;
	@UiField
	Image userImage;

	private final LoginButton loginButton = new LoginButton(true);

	private final static String API_KEY = "6e335d25f2e3b9e3248141ba47f520ef";

	private final FacebookLoginHandler loginHandler = new FacebookLoginHandler() {

		@Override
		public void loginStatusChanged(FacebookLoginEvent event) {
			if (Facebook.isLoggedIn()) {
				updateConnect();
			} else {
				userImage.setVisible(false);
			}
		}
	};

	public FacebookUi() {
		initWidget(uiBinder.createAndBindUi(this));

		init();
		flowPanel.add(loginButton);
	}

	private void init() {
		Facebook.init(API_KEY);
		Facebook.addLoginHandler(loginHandler);
	}

	private final void updateConnect() {
		Facebook.APIClient().users_getLoggedInUser(
				new AsyncCallback<FacebookUser>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onSuccess(FacebookUser result) {
						userImage.setUrl(result.getPic());
						userImage.setVisible(true);
					}

				}, UserField.PIC);
	}
}
